import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebView extends StatefulWidget {
  final String url;
  const WebView({super.key, required this.url});

  @override
  State<WebView> createState() => _WebViewState();
}

class _WebViewState extends State<WebView> {
  late final WebViewController _controller;
  String _pageTitle = '';

  @override
  void initState() {
    super.initState();
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted) // 允许 JavaScript
      ..setBackgroundColor(const Color(0x00000000)) // 背景透明
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageStarted: (String url) {
            // print('Page started loading: $url');
          },
          onPageFinished: (String url) async {
            // print('Page finished loading: $url');
            // 当页面加载完成时获取标题
            final String? title = await _controller.getTitle();
            setState(() {
              _pageTitle = title ?? '';
            });
          },
          onWebResourceError: (WebResourceError error) {
            // print('Error loading page: $error');
          },
        ),
      )
      ..loadRequest(Uri.parse(widget.url)); // 加载网页
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(title: Text(_pageTitle), backgroundColor: Colors.white),
      body: WebViewWidget(controller: _controller),
    );
  }
}
